//
//  Client_RF225_qArticleController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/9/11.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_feibuhuoController: HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDFounctionBottomViewDelegate , HDNumberInputCellDelegate , HDKeyboardInputCellDelegate{
//    //MARK: - property
    var firstAppear: Bool = true
    var piArticleCode: String?
    var piBin : String?
    var piToBin: String?
    var dataArray0:[[String : String]] = [["title" : "移入货位"] , ["title" :"建议移出货位"]]{
        didSet{
            self.tableView.reloadData()
        }
    }
    var dataArray1:[[String : String]] = [["title" : "移出货位"] , ["title" :"货品条码"] , ["title" : "货品名称"] , ["title" : "规格"] , ["title" : "批号"] , ["title" : "整件/零散"]]{
        didSet{
            self.tableView.reloadData()
        }
    }

    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["确认补货"])
        return view
    }()
    //MARK: - lifeCycle
    override func viewDidLoad() {
        self.tableView.register(HDBarcodeInputCell.self, forCellReuseIdentifier: "HDBarcodeInputCell")
        self.tableView.register(HDProductInfocell.self, forCellReuseIdentifier: "HDProductInfocell")
        self.tableView.register(HDNumberInputCell.self, forCellReuseIdentifier: "HDNumberInputCell")
        self.tableView.register(HDKeyboardInputCell.self, forCellReuseIdentifier: "HDKeyboardInputCell")
        self.tableView.addSubview(self.bottomView)
        self.tableView.bringSubview(toFront: self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
        super.viewDidLoad()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if self.firstAppear == true{
            let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! HDBarcodeInputCell
            cell.state = inputViewState.activated
            self.firstAppear = false
        }
    }
    //MARK: - delegate
  func clicKKeyboardReturn(_ cell: HDKeyboardInputCell){
    }
    func finishNumInput(_ cell: HDNumberInputCell) {
        
        if cell.titleView.text == "批号/日期"{
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
               self.showMessage("输入的批号不合法", success: false)
                return
            }
        }
        if cell.titleView.text == "整件/零散" {
            if Int(cell.boxNumberTextField.text ?? "0") == nil{
                self.showMessage("输入的整件数不合法", success: false)
                return
            }
            if Double(cell.bagNumberTextField.text ?? "0.0") == nil{
                 self.showMessage("输入的零散数不合法", success: false)
                return
            }
        }
        let numString = (cell.boxNumberTextField.text ?? "0") + "+" + (cell.bagNumberTextField.text ?? "0")
//        let numString = "1"
        self.getData(["piFromBin" : piBin! , "piToBin" : piToBin! , "piArticle" : self.downloadData["内码"]! , "piSpec" : self.downloadData["poSpec"]! , "piLot" : self.downloadData["poLot"]! , "piQpc" : numString , "piOperator" : (userInfo?.userName)!], bodyMethod: "updRpl2", suffix: "225", success: { (dict) in
            self.resetController(cell, nextItem: 0, nextSection: 0, message: "补货成功", success: true)
            }) { _ in 
              cell.state = inputViewState.wrong
        }
    }
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    func clickFounctionBottom(_ position: NSInteger) {
        let time = Double((self.tableView.contentOffset.y / KscreenHeight) * 0.5)
        let timeToRun = time > 1.2 ? 1.2 : time
        UIView.animate(withDuration: timeToRun, animations: {
//            self.tableView.contentOffset.y = 20
            self.tableView.scrollToRow(at: IndexPath(item: 0 , section: 0), at: UITableViewScrollPosition.top, animated: false)
            }, completion: { (true) in
                let cell = self.tableView.cellForRow(at: IndexPath(row: 5, section: 1)) as! HDNumberInputCell
                if cell.boxNumberTextField.text?.characters.count == 0 {
                    self.showMessage("请完善信息", success: false)
                    return
}
                self.finishNumInput(cell)
        }) 
    }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        cell.state = inputViewState.disabled
        let celltext = cell.codeInputView.textField.text
        if celltext?.characters.count == 0 {
            return
        }
        let indexpath = self.tableView.indexPath(for: cell)
        let position = ((indexpath as NSIndexPath?)?.section)! * 100 + ((indexpath as NSIndexPath?)?.row)!
        switch position {
        case 0:
          
            self.getData(["piToBin" : celltext!], bodyMethod: "GetRplToBin", suffix: nil, success: { (dict) in
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 1))
                self.dataArray0[1].updateValue(dict["poFromBin"] ?? "", forKey: "text")
                self.piToBin = celltext!
                let cell = self.tableView.cellForRow(at: IndexPath(item: 0, section: 1)) as! HDBarcodeInputCell
                cell.codeInputView.textField.text = dict["poFromBin"]
                }, failed: { _ in 
                    cell.state = inputViewState.wrong
            })
            break
        case 100:
            self.getData(["piFromBin" : celltext! ,"piArticle" : self.downloadData["poArticle"]! , "piOperator" : (userInfo?.userName)!], bodyMethod: "GetRplInfo2", suffix: nil, success: { (dict) in
                //显示信息
                self.piBin = celltext!
                let cell0 = self.tableView.cellForRow(at: IndexPath(row: 1, section: 1)) as! HDBarcodeInputCell
                cell0.codeInputView.textField.text = dict["poArticleCode"]?.components(separatedBy: ",").first
                self.piArticleCode = dict["poArticleCode"]?.components(separatedBy: ",").first
                self.dataArray1[2].updateValue(dict["poArticleName"]!, forKey: "text")
                let cell = self.tableView.cellForRow(at: IndexPath(item: 3, section: 1)) as! HDKeyboardInputCell
                cell.codeInputView.textField.text = dict["poSpec"]
                let cell2 = self.tableView.cellForRow(at: IndexPath(item: 4, section: 1)) as! HDKeyboardInputCell
                cell2.codeInputView.textField.text = dict["poLot"]
//                let cell3 = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 5, inSection: 1)) as! HDNumberInputCell
//                let array = dict["poQpc"]?.componentsSeparatedByString("+")
//                cell3.boxNumberTextField.text = array?.first
//                if array?.count > 1 {
//                    cell3.bagNumberTextField.text = array?.last
//                }else{
//                    cell3.bagNumberTextField.text = "0"
//                }
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 1, section: 1))
                }, failed: { _ in 
                    cell.state = inputViewState.wrong
            })
            break
        case 101:
            self.oneToManyHandler(self.piArticleCode!, piOwner: nil, piBin: piBin, success: { (dict) in
                if dict["内码"] == self.downloadData["poArticle"] {
                    let cell3 = self.tableView.cellForRow(at: IndexPath(item: 5, section: 1)) as! HDNumberInputCell
                    let array = self.downloadData["poQpc"]?.components(separatedBy: "+")
                    cell3.boxNumberTextField.text = array?.first
                    if array?.count > 1 {
                        cell3.bagNumberTextField.text = array?.last
                    }else{
                        cell3.bagNumberTextField.text = "0"
                    }

                    self.goNextCell(cell, nextInsexPath: IndexPath(item: 5, section: 1))
                }
                }, failed: {
                    self.showMessage("货品条码输入不符", success: false)
                    cell.state = inputViewState.wrong
            })
            break
        default:
            break
        }
    }
    //MARK: - private
    override func isEmpty() -> (Bool) {
        if let cell = self.tableView.cellForRow(at: IndexPath(item: 1, section: 0)) as? HDProductInfocell{
            if cell.textField.text?.characters.count > 0 {
                return false
            }else{
                return true
            }
        }else{
            return false
        }
//        if dataArray1.count > 0 {
//            return false
//        }else{
//            return true
//        }
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        default:
            return 6
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellOriginal:HDFounctionBaseCell?
        switch ((indexPath as NSIndexPath).section) * 100 + ((indexPath as NSIndexPath).row) {
        case 0:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.titleView.text = "移入货位"
            cell.InputDelegate = self
        case 1:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
            cellOriginal!.info = self.dataArray0[1]
        case 102:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDProductInfocell") as! HDProductInfocell
            cellOriginal!.info = self.dataArray1[2]
        case 103...104:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDKeyboardInputCell") as! HDKeyboardInputCell
            let cell = cellOriginal as! HDKeyboardInputCell
            cell.titleView.text = dataArray1[(indexPath as NSIndexPath).row]["title"]
            cell.InputDelegate = self
        case 105:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDNumberInputCell") as! HDNumberInputCell
            let cell = cellOriginal as! HDNumberInputCell
            cell.titleView.text = dataArray1[5]["title"]
            cell.precisionBox = 0
            cell.precisionBag = 2
            cell.delegate = self
        default:
            cellOriginal = tableView.dequeueReusableCell(withIdentifier: "HDBarcodeInputCell") as! HDBarcodeInputCell
            let cell = cellOriginal as! HDBarcodeInputCell
            cell.titleView.text = dataArray1[(indexPath as NSIndexPath).row]["title"]
            cell.InputDelegate = self
        }
        if !self.reuseFlag {
            cellOriginal?.clearContent()
        }
        return cellOriginal!
    }

    //MARK: - tableViewDelegate
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

            return nil
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 0:
            return 10
        default:
            return 0
        }
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
}
